<template>
	<div class="feedback-container">
		<div class="feedback-layout">
			<!-- 反馈提交表单 -->
			<el-card class="feedback-card">
				<template #header>
					<div class="card-header">
						<h2>意见反馈</h2>
						<p>您的反馈将帮助我们提升系统质量</p>
					</div>
				</template>

				<el-form :model="feedbackForm" :rules="rules" ref="feedbackFormRef" label-position="top">
					<el-form-item label="反馈类型" prop="type">
						<div class="radio-container">
							<el-radio-group v-model="feedbackForm.type">
								<el-radio label="功能优化">功能优化</el-radio>
								<el-radio label="新功能建议">新功能建议</el-radio>
								<el-radio label="性能问题">性能问题</el-radio>
								<el-radio label="功能异常">功能异常</el-radio>
								<el-radio label="Bug反馈">Bug反馈</el-radio>
							</el-radio-group>
						</div>
					</el-form-item>

					<el-form-item label="标题" prop="title" style="width: 60%">
						<el-input v-model="feedbackForm.title" placeholder="请输入反馈标题"></el-input>
					</el-form-item>

					<el-form-item label="详细描述" prop="content">
						<el-input
							v-model="feedbackForm.content"
							type="textarea"
							:rows="4"
							placeholder="请详细描述您的问题或建议..."
						></el-input>
					</el-form-item>

					<el-form-item label="联系方式(可选)" prop="contact" style="width: 40%">
						<el-input
							v-model="feedbackForm.contact"
							placeholder="请留下您的联系方式，方便我们及时回复"
						></el-input>
					</el-form-item>

					<el-form-item>
						<el-button
							type="primary"
							:loading="submitting"
							@click="submitFeedback"
							class="submit-btn"
						>
							提交反馈
						</el-button>
					</el-form-item>
				</el-form>
			</el-card>

			<!-- 反馈历史记录 -->
			<el-card class="history-card">
				<template #header>
					<div class="card-header">
						<h2>反馈历史</h2>
						<div class="header-actions">
							<el-button
								type="primary"
								size="small"
								@click="fetchFeedbackHistory"
								:loading="loading"
							>
								刷新
							</el-button>
							<el-button
								type="danger"
								size="small"
								@click="handleBatchDelete"
								:disabled="selectedFeedbacks.length === 0"
							>
								批量删除
							</el-button>
						</div>
					</div>
				</template>

				<div v-if="loading" class="loading-container">
					<el-skeleton :rows="3" animated />
				</div>

				<div v-else-if="feedbackHistory.length === 0" class="empty-data">
					<el-empty description="暂无反馈记录" />
				</div>

				<el-table
					v-else
					:data="feedbackHistory"
					style="width: 100%"
					@selection-change="handleSelectionChange"
					max-height="500"
				>
					<el-table-column type="selection" width="55" />
					<el-table-column prop="title" label="标题" show-overflow-tooltip>
						<template #default="scope">
							<el-link type="primary" :underline="false" @click="viewFeedbackDetail(scope.row)">
								{{ scope.row.title }}
							</el-link>
						</template>
					</el-table-column>
					<el-table-column prop="type" label="类型" width="100" />
					<el-table-column prop="status" label="状态" width="80">
						<template #default="scope">
							<el-tag :type="getStatusType(scope.row.status)">
								{{ getStatusText(scope.row.status) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="100">
						<template #default="scope">
							<el-button
								size="small"
								type="text"
								:icon="Delete"
								@click.stop="handleDelete(scope.row)"
								>删除</el-button
							>
						</template>
					</el-table-column>
				</el-table>
			</el-card>
		</div>

		<!-- 反馈详情对话框 -->
		<el-dialog v-model="dialogVisible" title="反馈详情" width="50%" destroy-on-close>
			<div v-if="currentFeedback" class="feedback-detail">
				<div class="detail-item">
					<span class="label">标题：</span>
					<span>{{ currentFeedback.title }}</span>
				</div>
				<div class="detail-item">
					<span class="label">类型：</span>
					<span>{{ currentFeedback.type }}</span>
				</div>
				<div class="detail-item">
					<span class="label">内容：</span>
					<p class="content">{{ currentFeedback.content }}</p>
				</div>
				<div class="detail-item">
					<span class="label">状态：</span>
					<el-tag :type="getStatusType(currentFeedback.status)">
						{{ getStatusText(currentFeedback.status) }}
					</el-tag>
				</div>
				<div class="detail-item" v-if="currentFeedback.contact">
					<span class="label">联系方式：</span>
					<span>{{ currentFeedback.contact }}</span>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { submitFeedBackService, getFeedBackService, deleteFeedBackService, getFeedBackListBySpecificService } from '@/api/feedBack'
import { useUserStore } from '@/stores'

// 表单引用
const feedbackFormRef = ref<FormInstance>()

// 表单数据
const feedbackForm = ref({
	type: '',
	title: '',
	content: '',
	contact: '',
	status: 'noResolved' // 默认状态为未解决
})

// 表单验证规则
const rules = reactive<FormRules>({
	type: [{ required: true, message: '请选择反馈类型', trigger: 'change' }],
	title: [
		{ required: true, message: '请输入反馈标题', trigger: 'blur' },
		{ min: 3, max: 50, message: '标题长度应在3到50个字符之间', trigger: 'blur' }
	],
	content: [
		{ required: true, message: '请输入详细描述', trigger: 'blur' },
		{ min: 10, max: 500, message: '描述长度应在10到500个字符之间', trigger: 'blur' }
	],
	contact: [
		{ pattern: /^1[3-9]\d{9}$|^.+@.+\..+$/, message: '请输入正确的手机号或邮箱', trigger: 'blur' }
	]
})

// 提交状态
const submitting = ref(false)

// 反馈历史数据
const feedbackHistory = ref<any[]>([])
const loading = ref(false)
const selectedFeedbacks = ref<any[]>([])
const dialogVisible = ref(false)
const currentFeedback = ref<any>(null)

// 获取反馈历史
const fetchFeedbackHistory = async () => {
	loading.value = true
	try {
		const userStore = useUserStore()
		const userId = userStore.userInfo.userInfo.userId

		const response = await getFeedBackListBySpecificService({ userId: userId })
		if (response.data.code === 1) {
			feedbackHistory.value = response.data.data || []
		} else {
			ElMessage.error(response.data.msg || '获取反馈历史失败')
		}
	} catch (error) {
		console.error('获取反馈历史失败:', error)
		ElMessage.error('获取反馈历史失败')
	} finally {
		loading.value = false
	}
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
	selectedFeedbacks.value = selection
}

// 处理单个删除
const handleDelete = async (row: any) => {
	try {
		await ElMessageBox.confirm('确定要删除这条反馈吗？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})

		const res = await deleteFeedBackService([row.id])
		if (res.data.code === 1) {
			ElMessage.success('删除成功')
			fetchFeedbackHistory()
		} else {
			ElMessage.error(res.data.msg || '删除失败')
		}
	} catch (error) {
		console.error('删除失败:', error)
		if (error !== 'cancel') {
			ElMessage.error('删除失败')
		}
	}
}

// 处理批量删除
const handleBatchDelete = async () => {
	if (selectedFeedbacks.value.length === 0) return

	try {
		await ElMessageBox.confirm(
			`确定要删除选中的 ${selectedFeedbacks.value.length} 条反馈吗？`,
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		)

		const ids = selectedFeedbacks.value.map((item) => item.id)
		const res = await deleteFeedBackService(ids)
		if (res.data.code === 1) {
			ElMessage.success('批量删除成功')
			fetchFeedbackHistory()
		} else {
			ElMessage.error(res.data.msg || '批量删除失败')
		}
	} catch (error) {
		console.error('批量删除失败:', error)
		if (error !== 'cancel') {
			ElMessage.error('批量删除失败')
		}
	}
}

// 查看反馈详情
const viewFeedbackDetail = (row: any) => {
	currentFeedback.value = row
	dialogVisible.value = true
}

// 获取状态类型
const getStatusType = (status: string) => {
	const statusMap: Record<string, string> = {
		resolved: 'success',
		resolving: 'warning',
		noResolved: 'danger'
	}
	return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
	const statusMap: Record<string, string> = {
		resolved: '已解决',
		resolving: '解决中',
		noResolved: '不解决'
	}
	return statusMap[status] || '未知'
}

// 提交反馈
const submitFeedback = async () => {
	if (!feedbackFormRef.value) return

	await feedbackFormRef.value.validate(async (valid, fields) => {
		if (valid) {
			submitting.value = true

			try {
				const userStore = useUserStore()
				// 准备提交的表单数据
				const feedbackData = {
					userId: userStore.userInfo.userInfo.userId,
					type: feedbackForm.value.type,
					title: feedbackForm.value.title,
					content: feedbackForm.value.content,
					contact: feedbackForm.value.contact,
					status: 'noResolved' // 默认设置为不解决，由管理员修改
				}

				// 提交反馈
				const response = await submitFeedBackService(feedbackData)
				if (response.data && response.data.code === 1) {
					ElMessage.success('反馈提交成功，感谢您的宝贵意见!')
					// 重置表单
					feedbackFormRef.value?.resetFields()
					// 刷新反馈历史
					fetchFeedbackHistory()
				} else {
					ElMessage.error(response.data?.msg || '提交失败，请稍后再试')
				}
			} catch (error) {
				console.error('提交失败:', error)
				ElMessage.error('提交失败，请稍后再试')
			} finally {
				submitting.value = false
			}
		} else {
			console.error('表单验证失败:', fields)
			ElMessage.error('请完善表单信息')
		}
	})
}

// 格式化日期
const formatDate = (dateString: string) => {
	if (!dateString) return ''
	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')

	return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 页面加载时获取反馈历史
onMounted(() => {
	fetchFeedbackHistory()
})
</script>

<style lang="scss" scoped>
.feedback-container {
	max-width: 1200px;
	margin: 20px auto;
	padding: 0 15px;

	.feedback-layout {
		display: flex;
		gap: 20px;

		@media (max-width: 992px) {
			flex-direction: column;
		}
	}

	.feedback-card,
	.history-card {
		border-radius: 8px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

		.card-header {
			margin-bottom: 10px;

			h2 {
				font-size: 24px;
				color: #303133;
				margin-bottom: 8px;
			}

			p {
				color: #909399;
				font-size: 14px;
				margin: 0;
			}

			.header-actions {
				display: flex;
				gap: 10px;
				margin-top: 10px;
			}
		}
	}

	.feedback-card {
		flex: 1;
		text-align: center;

		.radio-container {
			display: flex;
			flex-wrap: wrap;
			gap: 15px;

			.el-radio {
				margin-right: 15px;
			}
		}

		.submit-btn {
			width: 100%;
			padding: 12px;
			font-size: 16px;
			margin-top: 15px;
		}
	}

	.history-card {
		flex: 1;
		min-width: 450px;

		.loading-container {
			padding: 20px;
		}

		.empty-data {
			padding: 40px 0;
		}
	}

	.feedback-detail {
		.detail-item {
			margin-bottom: 15px;

			.label {
				font-weight: bold;
				color: #606266;
				margin-right: 10px;
			}

			.content {
				background-color: #f8f8f8;
				padding: 10px;
				border-radius: 4px;
				white-space: pre-wrap;
			}
		}
	}
}
</style>
